import {defineStore} from 'pinia';
import {store} from '@/store';
import {cloneDeep} from 'lodash-es';
import routes from '@/router/modules/routes';
import {flatMultiLevelRoutes, generateRoute} from '@/utils/routerHelper';
import {useCache} from '@/hooks/web/useCache';
import CacheKeys from '@/constants/CacheKeys';

const {wsCache} = useCache();

export interface PermissionState {
    curRoutes: AppRouteRecordRaw[];
    addRoutes: AppRouteRecordRaw[];
    menuTabRoutes: AppRouteRecordRaw[];
}

export const usePermissionStore = defineStore('permission', {
    state: (): PermissionState => ({
        curRoutes: [],
        addRoutes: [],
        menuTabRoutes: [],
    }),
    getters: {
        getRoutes(): AppRouteRecordRaw[] {
            return this.curRoutes;
        },
        getAddRoutes(): AppRouteRecordRaw[] {
            return flatMultiLevelRoutes(cloneDeep(this.addRoutes));
        },
        getMenuTabRoutes(): AppRouteRecordRaw[] {
            return this.menuTabRoutes;
        },
    },
    actions: {
        // 设置用户菜单路由
        setUserMenuRoute() {
            // 获得菜单列表，它在登录的时候，setUserInfoAction 方法中已经进行获取
            let res: AppCustomRouteRecordRaw[] = [];
            if (wsCache.get(CacheKeys.USER_MENUS)) {
                res = wsCache.get(CacheKeys.USER_MENUS) as AppCustomRouteRecordRaw[];
            }
            console.log('当前登录用户路由', res);
            // 生成路由
            const routeMap: AppRouteRecordRaw[] = generateRoute(res);
            // 动态路由，404一定要放到最后面
            this.addRoutes = routeMap.concat([
                {
                    path: '/:path(.*)*',
                    redirect: '/404',
                    name: '404Page',
                    meta: {
                        hidden: true,
                        breadcrumb: false,
                    },
                },
            ]);
            // 渲染菜单的所有路由
            this.curRoutes = cloneDeep(routes).concat(routeMap as any) as any;
        },
        setMenuTabRoutes(routes: AppRouteRecordRaw[]): void {
            this.menuTabRoutes = routes;
        },
    },
});

export const usePermissionStoreWithOut = () => {
    return usePermissionStore(store);
};
